package Controllers;

import Connection.FileUserManager;
import Connection.UserManager;
import Connection.WebUserManager;
import SwingComponents.UserRegisterPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class UserRegisterController {

    private PrincipalController principalController;
    private UserRegisterPanel userRegisterPanel;

    public UserRegisterController(PrincipalController principalController) {
        this.principalController = principalController;
    }

    public void execute() {
        userRegisterPanel = new UserRegisterPanel();
        principalController.getApplication().add(userRegisterPanel);
        principalController.getPrincipalPanel().setVisible(false);
        userRegisterPanel.setVisible(true);

        userRegisterPanel.getOkButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                registerUser();
            }
        });

        userRegisterPanel.getCancelButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                principalController.getPrincipalPanel().setVisible(true);
                principalController.getApplication().remove(userRegisterPanel);
            }
        });
    }

    private void registerUser() {
        UserManager userManager = new WebUserManager(principalController.getApplication());
        userManager.register(userRegisterPanel.getUsernameTextField().getText(),
                userRegisterPanel.getPasswordField().getPassword().toString(),
                userRegisterPanel.getNameTextField().getText(),
                userRegisterPanel.getSurnameTextField().getText(),
                userRegisterPanel.getEmailTextField().getText());
        principalController.getPrincipalPanel().setVisible(true);
        principalController.getApplication().remove(userRegisterPanel);
    }
}
